from rest_framework import serializers
from dvadmin.utils.serializers import CustomModelSerializer
from .models import Budget, FinancialMetrics
from dvadmin.system.models import Dept

class BudgetSerializer(CustomModelSerializer):
    """预算序列化器"""
    status_label = serializers.SerializerMethodField()
    department_name = serializers.SerializerMethodField()

    def get_status_label(self, obj):
        status_map = {
            'pending': '待审批',
            'approved': '已通过',
            'rejected': '已拒绝'
        }
        return status_map.get(obj.status, obj.status)

    def get_department_name(self, obj):
        try:
            dept = Dept.objects.get(key=obj.department)
            return dept.name
        except Dept.DoesNotExist:
            return obj.department

    class Meta:
        model = Budget
        fields = ['id', 'title', 'amount', 'department', 'department_name', 
                 'purpose', 'status', 'status_label', 'description', 'creator', 
                 'modifier', 'create_datetime', 'update_datetime']
        read_only_fields = ['status']

class BudgetCreateUpdateSerializer(CustomModelSerializer):
    """创建/更新预算序列化器"""
    def validate_department(self, value):
        try:
            dept = Dept.objects.get(key=value)
            return value
        except Dept.DoesNotExist:
            raise serializers.ValidationError("部门不存在")

    def validate_amount(self, value):
        """确保金额为数字类型"""
        try:
            return float(value)
        except (ValueError, TypeError):
            raise serializers.ValidationError("金额必须是有效的数字")
            
    def create(self, validated_data):
        validated_data['status'] = 'pending'
        return super().create(validated_data)

    class Meta:
        model = Budget
        fields = "__all__"
        read_only_fields = ['status']

class FinancialMetricsSerializer(CustomModelSerializer):
    """财务指标序列化器"""
    class Meta:
        model = FinancialMetrics
        fields = "__all__" 